/* 工具类 */

import http from './http.js'


//验证数值
function isNumber(num) {
	const reg = /^-?[0-9][0-9]?.?[0-9]*$/
	return reg.test(num)
}

//文本框输入时数值验证
function isInputNumber(num) {
	const reg = /^\d+\.?\d*?$/
	return reg.test(num)
}

//向上取整，保留两位小数
function FixedCeil2(num) {
	return (Math.ceil(num * 100) / 100).toFixed(2);
}

//不四舍五入，保留N位小数
function FixedCeilCoin(num, n) {
	let tmp = parseFloat(num).toFixed(n);
	return isNaN(tmp) ? (n == 2 ? '0.00' : (n == 6 ? '0.000000' : '0.00000000')) : tmp;
}


//提示信息
const msg = (title, duration = 1500, mask = false, icon = 'none') => {
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}


//六位数字验证码
function checkCode(code) {
	const flg = code.length != 6 || !isNumber(code)
	if (flg) {
		msg('输入六位数字验证码');
		return false
	}
	return true
}

//手机号码
function checkMobile(code) {
	const flg = code.length != 11 || !isNumber(code)
	if (flg) {
		msg('输入正确的手机号码');
		return false
	}
	return true
}

//6-12位密码验证
function checkPassword(pwd, pwdvlt) {
	const plen = pwd.length
	const pvltlen = pwdvlt.length
	if (plen < 6 || plen > 12 || pvltlen < 6 || pvltlen > 12) {
		msg('6-12 位的登录密码');
		return false
	}
	if (pwd != pwdvlt) {
		msg('两次输入密码不一致');
		return false
	}
	return true
}

/* 缓存历史搜索记录 */
function setSearchHistory(serachData, storeName) {
	if (serachData.length > 0) {
		let searchHistory = uni.getStorageSync(storeName);
		if (!searchHistory) searchHistory = [];
		let index = searchHistory.indexOf(serachData);
		if (index > -1) {
			searchHistory.splice(index, 1)
		}
		searchHistory.unshift(serachData);
		uni.setStorageSync(storeName, searchHistory);
	}
}

//判断session是否失效
async function loseSession() {
	if (Landing()) {
		//console.log('开始检查session是否失效 ')
		await testSession();
		//console.log('结束检查session是否失效 ')
	} else {
		//console.log('没有登录，不检查session是否失效')
	}
}

//检查session是否失效，如果失效用token登录
function testSession() {
	let resdata = new Promise(function(resolve, reject) {
		http.httpRequest('userWithdrawalAddress/userId', null, true).then(res => {
			//console.log('onShow检查token失效问题', res);
		});
	});
	return resdata;

}

/* 用户是否登录 */
function Landing() {
	let objUser = getUserStorage();
	return objUser ? true : false;
}

/* 获取用户缓存信息 */
function getUserStorage() {
	let objUser = uni.getStorageSync('login_user');
	if (objUser) {
		return JSON.parse(objUser);
	} else {
		return null;
	}
}

/* 设置用户缓存信息 */
function setUserStorage(user) {
	uni.setStorageSync('login_user', JSON.stringify(user));
}


/**
 * 更新用户信息
 * @param type {string} 用户字段名
 * @param value {string} 内容
 */
function updateUserStorage(type, value) {
	let objUser = getUserStorage();
	if (objUser) {
		switch (type) {
			case 'relationId':
				objUser.relationId = value;
				break;
			case 'wechat':
				objUser.wechat = value;
				break;
			case 'sex':
				objUser.sex = value;
				break;
			case 'nick':
				objUser.nick = value;
				break;
			case 'inviteCode':
				objUser.inviteCode = value;
				let tmpurl = objUser.inviteCodeUrl;
				let index = tmpurl.indexOf('=');
				if (index > -1) {
					objUser.inviteCodeUrl = tmpurl.substring(0, index) + "=$$" + value + "$$";
				}
				break;
		}
		setUserStorage(objUser);
	}
}

/* 清除用户缓存信息 */
function clearUserStorage() {
	uni.removeStorageSync('login_user');
	uni.removeStorageSync('JSESSIONID');
}

/* 获取用户渠道ID */
function getRelationId() {
	let rid = '';
	let objUser = getUserStorage();
	if (objUser) {
		rid = objUser.relationId;
	}
	return rid;
}

//判断是否存在ExistRelationId
async function ExistRelationId() {
	let flg = true;
	let objUser = getUserStorage();
	if (objUser) {
		if (!objUser.relationId) {
			flg = false;
			//#ifdef MP-WEIXIN
			//微信小程序
			uni.showToast({
				title: '为了保障您的收益，请在应用市场下载“聚链优选”APP以完成淘宝授权',
				icon: 'none',
				mask: true
			});
			//#endif
			//#ifdef APP-PLUS
			let flginit = await plugInit();
			let flguserinfo = await plugGetuserinfo();
			let flglogin = true;
			//console.log('flguserinfo',flguserinfo)
			if (!flguserinfo) {
				flglogin = await plugLogin();
			}
			if (flglogin) {
				let code = await plugGetpublisher();
				//console.log('code',code)
				if (code != '') {
					await codeToRelationId(code);
				}
			}
			//#endif
		}
	}
	return flg;
}

/* 获取淘口令 */
function taoKouLingCreate(promotedUrl) {
	let resdata = new Promise(function(resolve, reject) {
		let jMark = promotedUrl.indexOf('?') > -1 ? '&' : '?';
		promotedUrl = promotedUrl + jMark + 'relationId=' + getRelationId();
		//console.log('加getRelationId的链接', promotedUrl)
		const param = {
			text: '淘口令',
			url: promotedUrl
		};
		http.httpRequest('taobao/construction/tpwdCreate', param, true).then(res => {
			if (res._tranStatus) {
				//console.log('淘口令', res._data.model)
				resolve(res._data.model);
			} else {
				resolve('');
			}
		});
	});
	return resdata;
}

/* 获取短链 */
function shortUrlCreate(promotedUrl) {
	let promise = new Promise(function(resolve, reject) {
		let jMark = promotedUrl.indexOf('?') > -1 ? '&' : '?';
		promotedUrl = promotedUrl + jMark + 'relationId=' + getRelationId();
		//console.log('加getRelationId的链接', promotedUrl)
		const param = {
			url: promotedUrl
		};
		http.httpRequest('taobao/construction/spreadGet', param, true).then(res => {
			if (res._tranStatus) {
				//console.log('taobao/construction/spreadGet', res._data.shortUrl)
				resolve(res._data.shortUrl);
			} else {
				resolve(promotedUrl);
			}
		});
	});
	return promise;
}

//初始化
function plugInit() {
	//#ifdef APP-PLUS
	let resdata = new Promise(function(resolve, reject) {
		let plug = uni.requireNativePlugin('UZK-Alibcsdk');
		plug.init(result => {
			if (result.status) {
				resolve(true);
			} else {
				resolve(false);
			}
		});
	});
	return resdata;
	// #endif
}

//根据获取用户信息判断是否淘宝登录授权
function plugGetuserinfo() {
	//#ifdef APP-PLUS
	let resdata = new Promise(function(resolve, reject) {
		let plug = uni.requireNativePlugin('UZK-Alibcsdk');
		plug.getuserinfo(result => {
			if (result.status) {
				resolve(true);
			} else {
				resolve(false);
			}
		});
	});
	return resdata;
	//#endif
}

//淘宝授权登录
function plugLogin() {
	//#ifdef APP-PLUS
	let resdata = new Promise(function(resolve, reject) {
		let plug = uni.requireNativePlugin('UZK-Alibcsdk');
		plug.login(result => {
			if (result.status) {
				resolve(true);
			} else {
				resolve(false);
			}
		});
	});
	return resdata;
	//#endif
}

//code的方式进行授权备案
function plugGetpublisher() {
	//#ifdef APP-PLUS
	let resdata = new Promise(function(resolve, reject) {
		let plug = uni.requireNativePlugin('UZK-Alibcsdk');
		let ruri = 'http://127.0.0.1:12345/error';
		let url = 'https://oauth.m.taobao.com/authorize?response_type=code&client_id=29510703&redirect_uri=' + ruri +
			'&state=alink&view=web'
		plug.getpublisher({
				url: url
			},
			result => {
				if (result.status) {
					resolve(result.data.code);
				} else {
					resolve('');
				}
			}
		);
	});
	return resdata;
	//#endif
}

//通过code绑定RelationId
function codeToRelationId(code) {
	let resdata = new Promise(function(resolve, reject) {
		const param = {
			'sessionKey': code
		}
		http.httpRequest('user/bindRelationId', param, true).then(res => {
			if (res._tranStatus) {
				updateUserStorage('relationId', res._data.relationId)
				resolve(true)
			} else {
				msg(res._exceptionLocalizedMessage);
				resolve(false)
			}
		});
	});
	return resdata;
}

function searchClipboard11(cnt) {
	testClipboard(cnt).then(res => {
		console.log('searchClipboard', res)
		return res;
	})
}

//初始化剪切板内容
function initClipboard() {
	return {
		type: '',
		pItem: {
			pictUrl: '',
			title: '',
			commissionAmount: '',
			zkFinalPrice: '',
			couponAmount: ''
		}
	};
}

//联网查询剪切板内容
function searchClipboard(cnt) {
	//console.log('searchClipboard',cnt)
	let promise = new Promise(function(resolve, reject) {
		let answer = {
			type: '',
			pItem: {
				pictUrl: '',
				title: '',
				commissionAmount: '',
				zkFinalPrice: '',
				couponAmount: ''
			}
		}
		if (cnt.length > 0) {
			const param = {
				currentPage: 1,
				pageSize: 2,
				condition: {
					keyword: cnt,
					sortType: 'total_sales',
					sort: '_des'
				}
			};
			http.httpRequest('taobao/product/search', param, false).then(res => {
				//console.log('taobao/product/search',res)
				if (res._tranStatus) {

					let tmpItems = res._data.pageItems;
					if (tmpItems.length > 1) {
						answer.type = "text";
						resolve(answer);
					} else {
						answer.type = "link";
						answer.pItem = tmpItems[0];
						resolve(answer);
					}
				} else {
					answer.type = res._exceptionMessage == '300101' ? 'none' : "alert";
					resolve(answer);
				}
			});
		} else {
			resolve(answer);
		}
	});
	return promise;
}

//打开微信
function launchApp() {
	// #ifdef APP-PLUS
	// 判断平台
	if (plus.os.name == 'Android') {
		plus.runtime.launchApplication({
				pname: 'com.tencent.mm'
			},
			function(e) {
				//console.log('Open system default browser failed: ' + e.message);
			}
		);
	} else if (plus.os.name == 'iOS') {
		plus.runtime.launchApplication({
			action: 'weixin://'
		}, function(e) {
			//console.log('Open system default browser failed: ' + e.message);
		});
	}
	// #endif
}




export default {
	msg, //提示信息
	isNumber,//全部为数字
	isInputNumber, //文本框输入时数值验证
	checkCode, //六位数字验证码
	checkMobile, //手机号码
	checkPassword, //6-12位密码验证
	setSearchHistory, //缓存历史搜索记录
	Landing, //用户是否登录
	getUserStorage, //获取用户缓存信息
	setUserStorage, //设置用户缓存信息
	clearUserStorage, //清除用户缓存
	updateUserStorage, //更新用户relationid
	ExistRelationId, //是否存在Relation
	taoKouLingCreate, //获取淘口令
	shortUrlCreate, //获取短链
	getRelationId, //获取用户渠道ID
	FixedCeil2, //向上取整，保留两位小数
	FixedCeilCoin, //不四舍五入，保留N位小数
	loseSession, //检查session是否失效
	searchClipboard, //检查剪切板内容
	initClipboard, //初始化剪切板内容
	launchApp,//打开微信
}
